import { uniq, isEqual } from "lodash";
import queuePromise from "queue-promised";

import { Scheduler } from "./schedule";
import { JobParams } from "./store/models";

import eventBus from "~/utils/event";

const queue = queuePromise.queue;
const worker = queuePromise.worker;
const workerDispatch = {
  clearQueue: () => {
    queue._queues["queue"] = [];
    queue._waiters["queue"] = [];
  },
  getWaiter: (queueName: string) => {
    return queue.getWaiter(queueName);
  },
  push: (jobParams: JobParams) => {
    queue
      .push("queue", jobParams)
      .then((data: any) => {
        Scheduler.alreadyComplete.push(data.file);
        Scheduler.alreadyComplete = uniq(Scheduler.alreadyComplete);
        Scheduler.alreadyQueue = uniq(Scheduler.alreadyQueue);
        if (isEqual(Scheduler.alreadyComplete, Scheduler.alreadyQueue)) {
          console.log(`queueComplete`);
          eventBus.emit(`queueComplete`);
        }
      })
      .catch((e: { toString: () => any }) => {
        if (isEqual(Scheduler.alreadyComplete, Scheduler.alreadyQueue)) {
          console.log(`queue Complete`);
          eventBus.emit(`queueComplete`);
        }
      });
  },
  startWorkers: (job: (jobParams: any) => void) => {
    // Generate workers
    worker("queue", (jobParams: any) => {
      // This is worker functions. It can either return data or Promise
      return job(jobParams);
    });
  },
};

export { workerDispatch };
